package nu.mine.tbje.easyEDT;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class vcalServlet extends HttpServlet {

	    public void init()
	        throws ServletException
	    {
	    }

	    public void doGet( HttpServletRequest req, HttpServletResponse resp )
	        throws ServletException, IOException{

	    	String uri = req.getRequestURI();
	    	int id = 870;
	    	int week = 0;
			Pattern p1 = Pattern.compile("Groupe([0-9]*)Week([0-9]{2})");
			Pattern p2 = Pattern.compile("Groupe([0-9]*)");
			Matcher m;
			m = p1.matcher(uri);
			if (m.find()){
				id = Integer.parseInt(m.group(1));
				week = Integer.parseInt(m.group(2));
			} else {
				m = p2.matcher(uri);
				if (m.find()){
					id = Integer.parseInt(m.group(1));
					week = -1;
				} else {
			        resp.setContentType("text/html");
			        PrintWriter writer = null;
			        try
			        {
			            writer = resp.getWriter();
			            writer.write("Invalid url");
			        }
			        catch (IOException e)
			        {
			            e.printStackTrace();
			        }
			        finally
			        {
			            writer.flush();
			            writer.close();
			        }
				}
			}

			// Set the content type
	        resp.setContentType("text/x-vcalendar");
	        resp.setCharacterEncoding("UTF-8");

	        // Generate the HTML
	        vcalWriter.getWeek(week, id, resp.getOutputStream());

	    }

	}

